// \u4e00-\u9fa5] 中文验证规则
import wxvalidate from'wechat-validate'
Page({
  behaviors: [wxvalidate],
  data: {
    point:'',
    building:"",
    room:'',
    name:"",
    gender:"",
    mobile:"",
    idcardFrontUrl: '',
    idcardBackUrl: '',
    
  },
  rules: {
    name: [
      { required: true, message: '业主姓名不能为空!' },
      { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: '业主姓名只能为中文!' },
    ],
    mobile: [
      { required: true, message: '业主手机号不能为空!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号!' },
    ],
    idcardFrontUrl: [
      { required: true, message: '请上传身份证国徽面!' }
    ],
    idcardBackUrl: [
      { required: true, message: '请上传身份证照片面!' }
    ],
  },
  onLoad({point,building,room,id}){
    this.getHouseDetail(id)
    wx.setNavigationBarTitle({
      title:id ?  '修改房屋':"增加房屋"
    })
    this.setData({point,building,room})

  },
  async getHouseDetail(id){
      if(!id) return wx.utils.toast('参数有误')
      const {data:houseDetail,code}=await wx.http.get('/room/'+id)
      console.log(houseDetail);
      if(code!==10000)return wx.utils.toast()
      this.setData({...houseDetail})

},

   // 上传身份证照片
   async uploadPicture(ev) {
    // 区分用户上传的是正面或反面
    const type = ev.mark.type
    console.log(ev);
console.log(type);
    try {
      // 打开相册或拍照
      const media = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed'],
      })

      // 调用 API 上传图片
      wx.uploadFile({
        url: wx.http.baseURL + '/upload',
        filePath: media.tempFiles[0].tempFilePath,
        name: 'file',
        header: {
          Authorization: 'Bearer ' + getApp().token,
        },
        success: (result) => {
          // 处理返回的 json 数据
          const data = JSON.parse(result.data)
          // 判断接口是否调用成功
          
          if (data.code !== 10000) return wx.utils.toast('上传图片失败!')
          // 渲染数据
          this.setData({[type]: data.data.url})
        },
      })
    } catch (err) {
      // 获取图片失败
      console.log(err)
    }
  },
  async submitForm(){
    if(!this.validate()) return

  //  eslint-disable-next-line no-unused-vars
   const { __webviewId__, status, ...data } = this.data
    // 调用接口
    const { code } = await wx.http.post('/room',data)
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast('提交数据失败!')
    // 返回房屋列表页面
    wx.navigateBack({ delta:this.data.id? 2:4 })
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark.type
    this.setData({ [type]: '' })
  },
})
